var utils = require('../../utils/util.js');
var base64Js = require('../../utils/base64.js');
var md5Js = require('../../utils/md5.js');
var app = getApp();
var object = {};
var tag_box = [];
object.data = {};
Page({
  data: {
    activeIndex: 0,
    productList: [],//一般默认为空，你返回的数据是数组，就空数组，如果是对象就是是{} 空对象对象，
    parent_brand: [],//申明一个空得一级分类数组
    actionSheetHidden: true,
    sku_info_checkout: [],
    product_info: [],
    index: 0,
    num: 1,
    animationData: {},
    product_tag: {}
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },
  onLoad: function (options) {
    try {
      var _this = this;
      //获取缓存的用户对象信息
      var user_info = wx.getStorageSync('user_info');
      //如果用户信息不为空则请求首页接口获取产品等信息。
      if (user_info) {
        var request_data = user_info.user_itmes;
        var uid = request_data.id.toString();
        var private_key = user_info.private_key;
        var t = new Date().getTime().toString();
        var k = md5Js.hex_md5(private_key + t);//key
        var parms_url = app.request_url + 'C_ProductList/?';
        parms_url += 'enterpriseId=' + request_data.enterpriseId;
        parms_url += '&channelId=' + request_data.channelId;
        parms_url += '&uid=' + request_data.id;
        parms_url += '&userType=' + request_data.type;
        parms_url += '&t=' + t;
        parms_url += '&k=' + k;
        parms_url += '&v=' + app.version;;
        parms_url += '&l=999';
        // parms_url = 'https://rest.test.freshqiao.com/C_ProductList/?enterpriseId=79&channelId=200&uid=100000261&l=99999&userType=1&t=1484718374429&k=39470b5e8f90281503a6f3a4be286031&uid=100000261&v=2';
        //调用产品页接口
        wx.request({
          url: parms_url,
          method: 'GET',
          success: function (res) {
            var respones = res;
            console.log(respones);
            //请求成功分配模板变量
            if ((respones.statusCode == '200') && (respones.data.Success == 1)) {
              var data = respones.data.CallInfo;
              if (data.product_list != false) {
                var data_product = data.product_list;
                var product_length = data_product.length;
                for (var i = 0; i < product_length; i++) {
                  var price = data_product[i].sku_info[0].sellprice;
                  var scell_price = 0
                  if (price) {
                    scell_price = price;
                  }
                  data_product[i].scell_price_string = scell_price;
                }
                //将数据重新整理以父分类
                var map = {};
                var dest = [];
                var content = [];
                for (var i = 0; i < data_product.length; i++) {
                  var ai = data_product[i];
                  if (!map[ai.parent_brand_id]) {
                    dest.push({
                      parent_brand_name: ai.parent_brand_name,
                      parent_brand_id: ai.parent_brand_id,
                      data: [ai]
                    });
                    map[ai.parent_brand_id] = ai;
                  } else {
                    for (var j = 0; j < dest.length; j++) {
                      var dj = dest[j];
                      if (dj.parent_brand_id == ai.parent_brand_id) {
                        dj.data.push(ai);
                        break;
                      }
                    }
                  }
                }
                //用于搜索
                wx.setStorageSync('product_info', data_product);
                //将子分类取出
                // for(var k in dest){
                //    for(var y in dest[k].data){
                //       dest[k].data.push(dest[k].data[y].brandname);
                //   }
                // }
                console.log(dest);
                _this.setData({
                  productList: res.data,
                  parent_brand: dest,
                  content: dest[0].data
                })
              }
            }
          }
        })
      }
    } catch (e) {
      console.log('error=>' + e.message); return false;
    }
  },
  onReady: function () {
    // 页面渲染完成
    var _this = this;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowHeight);
        _this.setData({
          allHeight: res.windowHeight,
        })
      }
    })
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },

  //搜索
  showInput: function () {
    wx.navigateTo({
      url: '../search/search',
    })
  },

  bindMinus: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.num;
    // 如果只有1件了，就不允许再减了
    if (num > 1) {
      num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses;
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatuses: minusStatus
    });
  },
  bindPlus: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.num;
    // 自增
    num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses;
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatuses: minusStatus
    });
  },

  showModal: function (e) {
    // 显示遮罩层
    var sku_info = e.currentTarget.dataset.skuinfo;
    var product_name = e.currentTarget.dataset.productname;
    var productinfo = e.currentTarget.dataset.productinfo;
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      product_name: product_name,
      sku_info: sku_info,
      product_info: productinfo,
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  //选择属性
  radioChange: function (e) {
    this.setData({
      sku_info_checkout: e.currentTarget.dataset.skuinfo,
      activeIndex: e.currentTarget.dataset.index
    });
  },

  //点击购物车图片时添加商品
  submit: function (e) {
    var cart = require('../../utils/cart.js');
    cart.submitcart(e, this)
  },

  //点击产品时进入产品详情页
  productdetail: function (e) {
    var id = e.target.dataset.id;
    wx.navigateTo({
      url: '../shopdetail/shopdetail?id=' + id,
    })

  },

  //点击父分类
  changeTab: function (e) {
    this.setData({
      activeIndex: e.currentTarget.dataset.index,
      content: e.currentTarget.dataset.brandname,
      targetCate: e.currentTarget.dataset.cateId,
    })
  },
  //列表排序
  sortProduct: function (event) {
    var img_icon = '../../images/sort.png';
    var sort_type = event.currentTarget.dataset.type;
    var sort_sign = event.currentTarget.dataset.sign;
    var sort_cate = event.currentTarget.dataset.cate;
    var sort_level = event.currentTarget.dataset.level;

    /* 产品数据 */
    var product_box = [];
    if (sort_level == 'list') {
      var product_list = wx.getStorageSync('product_info');
      for (var i = 0; i < product_list.length; i++) {
        if (product_list[i].parent_brand_id == sort_cate || product_list[i].brand_id == sort_cate) {
          product_box.push(product_list[i]);
        }
      }
    } else if (sort_level == 'search') {
      var product_list = wx.getStorageSync('product_search');
      for (var i = 0; i < product_list.length; i++) {
        product_box.push(product_list[i]);
      }
    }

    /* 尝试排序 */
    switch (sort_type) {
      case 'price':
        this.arraySort(product_box, 'sort_price');
        console.log(product_box);
        if (sort_sign == 'up') {
          this.setData({
            priceSort: 'down',
            saleSort: '',
            priceIcon: '../../images/sort_down.png',
            saleIcon: img_icon,
            content: product_box
          })
        } else {
          product_box.reverse();
          this.setData({
            priceSort: 'up',
            saleSort: '',
            priceIcon: '../../images/sort_up.png',
            saleIcon: img_icon,
            content: product_box
          })
        }
        break;
      case 'sale':
        this.arraySort(product_box, 'sales_valume');
        if (sort_sign == 'up') {
          this.setData({
            saleSort: 'down',
            priceSort: '',
            saleIcon: '../../images/sort_down.png',
            priceIcon: img_icon,
            content: product_box
          })
        } else {
          product_box.reverse();
          this.setData({
            saleSort: 'up',
            priceSort: '',
            saleIcon: '../../images/sort_up.png',
            priceIcon: img_icon,
            content: product_box
          })
        }
        break;
      case 'normal':
        this.arraySort(product_box, 'sort');
        this.setData({
          saleSort: '',
          priceSort: '',
          saleIcon: img_icon,
          priceIcon: img_icon,
          content: product_box
        })
      default:
        break;
    }
    this.setData({
      imgIcon: img_icon
    })
  },

  //数组排序函数
  arraySort: function (arr, key) {
    arr.sort(function (a, b) {
      return b[key] - a[key];
    });
  },

  //显示搜索表单
  showSearch: function () {
    var product_tag = wx.getStorageSync('product_tags');
    if (!product_tag) {
      var user_info = wx.getStorageSync('user_info');
      var _this = this;

      var request_data = user_info.user_itmes;
      var uid = request_data.id.toString();
      var private_key = user_info.private_key;
      var t = new Date().getTime().toString();
      var k = md5Js.hex_md5(private_key + t);//key
      var parms_url = app.request_url + 'C_ProductTags/?';
      parms_url += 'enterpriseId=' + request_data.enterpriseId;
      parms_url += '&channelId=' + request_data.channelId;
      parms_url += '&uid=' + request_data.id;
      parms_url += '&userType=' + request_data.type;
      parms_url += '&t=' + t;
      parms_url += '&k=' + k;
      parms_url += '&v=' + app.version;;
      parms_url += '&l=999';
      // parms_url = 'https://rest.test.freshqiao.com/C_ProductList/?enterpriseId=79&channelId=200&uid=100000261&l=99999&userType=1&t=1484718374429&k=39470b5e8f90281503a6f3a4be286031&uid=100000261&v=2';
      //调用产品页接口
      wx.request({
        url: parms_url,
        method: 'GET',
        success: function (res) {
          if (res.data.CallInfo['tags']) {
            var tags = res.data.CallInfo['tags'];
            _this.setData({
              product_tag: tags
            })
            wx.setStorageSync('product_tags', tags);
          }
        },
      })
    } else {
      this.setData({
        product_tag: product_tag
      })
    }

    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease",
      delay: 0
    });

    this.animation = animation;

    animation.translateX('25%').step();
    this.setData({
      searchData: animation.export(),
      showSearchStatus: true
    })
  },

  //隐藏搜索表单项
  hideSearchModal: function () {
    this.setData({
      showSearchStatus: false
    })
  },

  //选择标签
  checkTag: function (event) {
    var product_tag = wx.getStorageSync('product_tags');
    var group = event.currentTarget.dataset.group;
    var index = event.currentTarget.dataset.index;

    if (product_tag[group].child_tag[index].class == ' tag_check') {
      product_tag[group].child_tag[index].class = '';
    } else {
      product_tag[group].child_tag[index].class = ' tag_check';
    }
    this.setData({
      product_tag: product_tag
    })
    wx.setStorageSync('product_tags', product_tag);
  },

  //重置搜索
  searchReset: function (event) {
    this.setData({
      max_price: '',
      min_price: '',
    })
    var product_tag = wx.getStorageSync('product_tags');
    if (product_tag.length) {
      for (var i = 0; i < product_tag.length; i++) {
        for (var j = 0; j < product_tag[i].child_tag.length; j++) {
          product_tag[i].child_tag[j].class = '';
        }
      }
      this.setData({
        product_tag: product_tag
      })
      wx.setStorageSync('product_tags', product_tag);
    }
  },

  //返回列表
  searchBack: function (event) {
    var product_box = [];
    var sort_cate = 0;

    var product_list = wx.getStorageSync('product_info');
    for (var i = 0; i < product_list.length; i++) {
      if (product_list[i].parent_brand_id == sort_cate || product_list[i].brand_id == sort_cate) {
        product_box.push(product_list[i]);
      }
    }
    this.setData({
      showSearchStatus: false,
      showSearchCon: false,
      content: product_box
    })
  },

  //输入最低价
  setMinPrice: function (event) {
    var price = event.detail.value;
    this.setData({
      minPrice: price
    })
  },

  setMaxPrice: function (event) {
    var price = event.detail.value;
    this.setData({
      maxPrice: price
    })
  },

  //提交搜索
  searchSubmit: function (event) {
    //组织标签
    var product_tag = wx.getStorageSync('product_tags');
    var tag_submit = '';
    if (product_tag.length) {
      var tag_arr = [];
      for (var i = 0; i < product_tag.length; i++) {
        var tag_str = '';
        var tag_label = [];
        for (var j = 0; j < product_tag[i].child_tag.length; j++) {
          if (product_tag[i].child_tag[j].class == ' tag_check') {
            tag_label.push(product_tag[i].child_tag[j].id);
          }
        }
        if (tag_label.length) {
          tag_str = tag_label.join();
          tag_arr.push(product_tag[i].id + ':' + tag_str);
        }
      }
    }
    if (tag_arr.length) {
      tag_submit = tag_arr.join(';');
    } else {
      tag_submit = '';
    }

    //获取价格区间
    var min_price = event.currentTarget.dataset.minPrice;
    var max_price = event.currentTarget.dataset.maxPrice;

    //请求接口
    var _this = this;
    //获取缓存的用户对象信息
    var user_info = wx.getStorageSync('user_info');
    //如果用户信息不为空则请求首页接口获取产品等信息。
    if (user_info) {
      var request_data = user_info.user_itmes;
      var uid = request_data.id.toString();
      var private_key = user_info.private_key;
      var t = new Date().getTime().toString();
      var k = md5Js.hex_md5(private_key + t);//key
      var parms_url = app.request_url + 'C_ProductList/?';
      parms_url += 'enterpriseId=' + request_data.enterpriseId;
      parms_url += '&channelId=' + request_data.channelId;
      parms_url += '&uid=' + request_data.id;
      parms_url += '&userType=' + request_data.type;
      parms_url += '&minPrice=' + min_price;
      parms_url += '&maxPrice=' + max_price;
      parms_url += '&t=' + t;
      parms_url += '&k=' + k;
      parms_url += '&v=' + app.version;;
      parms_url += '&l=999';
      //调用产品页接口
      wx.request({
        url: parms_url,
        method: 'GET',
        success: function (res) {
          var respones = res;
          console.log(respones);
          //请求成功分配模板变量
          if ((respones.statusCode == '200') && (respones.data.Success == 1)) {
            var data = respones.data.CallInfo;
            if (data.product_list != false) {
              var data_product = data.product_list;
              var product_length = data_product.length;
              for (var i = 0; i < product_length; i++) {
                var price = data_product[i].sku_info[0].sellprice;
                var scell_price = 0
                if (price) {
                  scell_price = price;
                }
                data_product[i].scell_price_string = scell_price;
              }
              _this.setData({
                content: data_product
              })
              wx.setStorageSync('product_search', data_product);
            }
          }
        }
      })
    }

    this.setData({
      showSearchStatus: false,
      showSearchCon: true,
      tag_submit: tag_submit
    })
  }

})

